package com.srd.phone.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.shengrongdai.srd.R;
import com.srd.phone.activity.CarouselActivity;
import com.srd.phone.activity.MainActivity;
import com.srd.phone.activity.NoticeDetailActivity;
import com.srd.phone.activity.NoticeListActivity;
import com.srd.phone.activity.TenderInvestActivity;
import com.srd.phone.adapter.TabTenderListLicaiAdapter;
import com.srd.phone.bean.CarouselInfo;
import com.srd.phone.bean.NoticeInfo;
import com.srd.phone.bean.TabMine;
import com.srd.phone.bean.TenderInfo;
import com.srd.phone.mvp.presenters.TabHomePresenter;
import com.srd.phone.utils.Constants;
import com.srd.phone.utils.autoscrollpage.FlyBanner;
import com.srd.phone.utils.views.HornViewFlipper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页fragment
 */
public class TabHomeFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener, View.OnClickListener {

    private View root;
    private PullToRefreshListView lv_list;
    //平台
    private FlyBanner banner_1;
    private TextView tv_touzi;
    private TextView tv_shouyi;
    private TextView tv_regis_person;
    //个人账户
    private LinearLayout ll_person_account;
    private TextView tv_person_touzi;
    private TextView tv_person_shouyi;
    private TextView tv_person_yue;

    private HornViewFlipper hvf;
    private TextView tv_more_notices; //资讯公告,查看更多
    private TextView tv_notice1; //资讯公告1
    private TextView tv_notice2; //资讯公告2
    private TextView tv_more_touzi; //更多产品

    private TabHomePresenter tabHomePresenter;
    private TabTenderListLicaiAdapter adapter;
    private List<TenderInfo> list = new ArrayList<>();

    private String urlsxCircuitImg = Constants.BASEURL + "homepageApp/sxCircuitImg"; //轮播图
    private String urlHomePageBmarkList = Constants.BASEURL + "homepageApp/homePageBmarkList"; //标的数据列表接口
    private String urlStotal = Constants.BASEURL + "homepageApp/stotal"; // 获取平台数据接口
    private String urlPersonAccount = Constants.OVERVIEWS; //获取个人数据接口
    private String urlNewsNotice = "http://192.168.1.224:8080/api/a/GetArtic"; //获取文章公告
    private int page = 1;
    List<CarouselInfo> carouselList = new ArrayList<>();

    List<String> hornList = new ArrayList<>(); //小喇叭数据集合，现在是测试数据

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (root == null) {
            root = inflater.inflate(R.layout.fragment_tab_home, container, false);
            initView();
            initData();
        }
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mContext.getLoginStatus()) {
            ll_person_account.setVisibility(View.GONE);
            getPersonAccountData();
        } else {
            ll_person_account.setVisibility(View.GONE);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void initView() {
        lv_list = (PullToRefreshListView) root.findViewById(R.id.lv_list);
        lv_list.getRefreshableView().addHeaderView(getActivity().getLayoutInflater().inflate(R.layout.fragment_tab_home_head, null));
        tv_more_touzi = (TextView) root.findViewById(R.id.tv_more_touzi);
        tv_more_touzi.setOnClickListener(this);
        lv_list.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        lv_list.setOnRefreshListener(this);
        lv_list.setScrollingWhileRefreshingEnabled(true); //正在刷新的时候，可以滑动界面
        banner_1 = (FlyBanner) root.findViewById(R.id.banner_1);
        tv_touzi = (TextView) root.findViewById(R.id.tv_touzi);
        tv_shouyi = (TextView) root.findViewById(R.id.tv_shouyi);
        ll_person_account = (LinearLayout) root.findViewById(R.id.ll_person_account);
        tv_regis_person = (TextView) root.findViewById(R.id.tv_regis_person);
        tv_person_touzi = (TextView) root.findViewById(R.id.tv_person_touzi);
        tv_person_shouyi = (TextView) root.findViewById(R.id.tv_person_shouyi);
        tv_person_yue = (TextView) root.findViewById(R.id.tv_person_yue);
        tv_more_notices = (TextView) root.findViewById(R.id.tv_more_notices);
        tv_more_notices.setOnClickListener(this);
        tv_notice1 = (TextView) root.findViewById(R.id.tv_notice1);
        tv_notice2 = (TextView) root.findViewById(R.id.tv_notice2);
        tv_more_touzi = (TextView) root.findViewById(R.id.tv_more_touzi);
        hvf = (HornViewFlipper)root.findViewById(R.id.hvf);
    }

    @Override
    public void initData() {
        banner_1.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String url = carouselList.get(position).src;
                Intent intent = new Intent(mContext, CarouselActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
            }
        });
        adapter = new TabTenderListLicaiAdapter(mContext);
        lv_list.setAdapter(adapter);
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, TenderInvestActivity.class);
                intent.putExtra("info", list.get(position - 2));
                startActivity(intent);
            }
        });
        presenter = new TabHomePresenter(requestQueue, this);
        tabHomePresenter = (TabHomePresenter) presenter;
        setUrlArrs(urlsxCircuitImg, urlHomePageBmarkList, urlStotal, urlPersonAccount, urlNewsNotice);
        getCarousel(); //获取轮播图
        getPlatformData(); //获取平台数据
        getTenderData(); //获取标的数据
        getNotice(); //文章公告
        hornData();
    }

    /**
     * 小喇叭数据赋值
     */
    private void hornData(){
        for (int i = 0; i < 10; i++) {
            hornList.add(i + "");
        }
        hvf.setData(hornList);
        hvf.setFlipInterval(2000); //2秒的间隔时间
        hvf.startFlipping();
    }

    //获取轮播图
    private void getCarousel() {
        Map<String, String> map = new HashMap<>();
        map.put("isenable", "1");
        map.put("position", "86");
        map.put("direction", "87");
        tabHomePresenter.requestPostData(urlsxCircuitImg, map);
    }

    //获取平台数据
    private void getPlatformData() {
        tabHomePresenter.requestPostData(urlStotal);
    }

    //获取我的账户信息
    private void getPersonAccountData() {
        //tabHomePresenter.requestData(urlPersonAccount);
    }

    //资讯公告
    private void getNotice() {
        urlNewsNotice += "?siteId=4&stat=2";
        tabHomePresenter.requestGetData(urlNewsNotice);
    }

    //获取标的数据
    private void getTenderData() {
        Map<String, String> map = new HashMap<>();
        map.put("stat", "54,62");
        map.put("page", "" + page);
        tabHomePresenter.requestPostData(urlHomePageBmarkList, map);
    }

    //赋值我的账户信息
    private void setPersonAccountData(TabMine tabMine) {
        tabHomePresenter.setPersonTextSpan(tv_person_touzi, tabMine.sinves);
        tabHomePresenter.setPersonTextSpan(tv_person_shouyi, tabMine.sprofit);
        tabHomePresenter.setPersonTextSpan(tv_person_yue, tabMine.available);
    }

    //赋值资讯公告的值
    private void setNoticeData(final List<NoticeInfo> list) {
        if (list.size() == 0) {
            tv_notice1.setVisibility(View.GONE);
            tv_notice2.setVisibility(View.GONE);
        } else if (list.size() == 1) {
            tv_notice1.setVisibility(View.VISIBLE);
            tv_notice1.setText(list.get(0).title);
        } else if (list.size() >= 2) {
            tv_notice1.setVisibility(View.VISIBLE);
            tv_notice2.setVisibility(View.VISIBLE);
            tv_notice1.setText(list.get(0).title);
            tv_notice2.setText(list.get(1).title);
        }
        tv_notice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, NoticeDetailActivity.class);
                intent.putExtra("id", list.get(0).id);
                startActivity(intent);
            }
        });
        tv_notice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, NoticeDetailActivity.class);
                intent.putExtra("id", list.get(1).id);
                startActivity(intent);
            }
        });
    }

    @Override
    public void returnData(String tag, String data) {
        super.returnData(tag, data);
        mContext.cancelWaitingDialog();
        lv_list.onRefreshComplete();
        if (tag == urlsxCircuitImg) { //轮播图
            carouselList = CarouselInfo.parser(data);
            List<String> arrList = new ArrayList<>();
            for (CarouselInfo carInfo : carouselList) {
                arrList.add(carInfo.imgsrc);
            }
            banner_1.setImagesUrl(arrList);
        } else if (tag == urlHomePageBmarkList) { //标的信息
            List<TenderInfo> list0 = TenderInfo.parseTenderListData(data);
            list.addAll(list0);
            adapter.setData(list);
            if (list0.size() != 0) {
                page++;
            }
        } else if (tag == urlStotal) { //平台数据
            try {
                JSONObject jsonObject = new JSONObject(data);
                double smoneys = jsonObject.optDouble("smoneys", 0);
                double sprofit = jsonObject.optDouble("sprofit", 0);
                int suser = jsonObject.optInt("suser");
                tabHomePresenter.setTextSpan(tv_touzi, "投资", tabHomePresenter.getFormatMoney(smoneys), "元");
                tabHomePresenter.setTextSpan(tv_shouyi, "收益", tabHomePresenter.getFormatMoney(sprofit), "元");
                tabHomePresenter.setTextSpan(tv_regis_person, "注册人数", suser + "", "人");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (tag == urlPersonAccount) { //我的账户信息
            setPersonAccountData(TabMine.parse(data));
        } else if (tag == urlNewsNotice) { //文章公告
            setNoticeData(NoticeInfo.parser(data));
        }
    }

    @Override
    public void onError(String tag, VolleyError error) {
        super.onError(tag, error);
        mContext.cancelWaitingDialog();
        lv_list.onRefreshComplete();
    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        Map<String, String> map = new HashMap<>();
        map.put("stat", "54,62");
        map.put("page", "" + page);
        tabHomePresenter.requestPostData(urlHomePageBmarkList, map);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_more_touzi:
                ((MainActivity) getActivity()).setCurrentItem(1);
                break;
            case R.id.tv_more_notices:
                gotoActivity(NoticeListActivity.class);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        banner_1.stopAutoPlay();
        hvf.stopFlipping();
    }
}
